<template>
  <el-dialog
    ref="refDlg"
    title="单号图纸上传"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="700px"
    @close="closeDialog"
  >
    <div>
      <div style="margin-bottom:10px">
        <el-button type="primary" size="mini" @click="handleAdd()">新增</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="fileList"
        border
        max-height="300"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column width="80" show-overflow-tooltip prop="attachmentName" label="预览">
          <template slot-scope="scope">
            <div @click="handlePreview(scope.row,scope.$index)">
              <el-image
                class="file-box"
                :src="filterURL(scope.row.attachmentUrl)"
                fit="cover"
              >
                <div slot="error">
                  <span>文件</span>
                </div>
              </el-image>
            </div>

          </template>
        </el-table-column>
        <el-table-column min-width="130" show-overflow-tooltip prop="attachmentName" label="附件名称">
          <template slot-scope="scope">
            <el-input v-model="scope.row.attachmentName" size="mini" />
          </template>
        </el-table-column>
        <el-table-column width="80" prop="createBy" label="上传人" />
        <el-table-column min-width="110" show-overflow-tooltip prop="createTime" label="上传时间" />
        <el-table-column min-width="110" fixed="right" label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" @click="handlePreview(scope.row)">预览</el-button> -->
            <a
              style="text-decoration: none;color:#39c094;font-size: 12px;"
              :href="url+'/'+scope.row.attachmentUrl"
              :download="scope.row.attachmentName"
            >
              下载
            </a>
            <el-button type="text" size="small" @click="handleDelete(scope.row.id,scope.$index)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <input ref="fileInput" multiple type="file" accept="*" style="display: none" @change="getFile">

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="imgDialogVisible"
      :on-close="handleCloseImg"
      :url-list="previewImgs"
    />
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" :disabled="loading" type="primary" @click="submitForm(0)">保存</el-button>
      <el-button size="mini" :disabled="loading" type="primary" @click="submitForm(1)">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fileUploadBatch, postConfigAttachmentTemplate } from '@/api/common.js'
import { queryDetail, saveOrderPicUpload } from '@/api/autoDesignTask'
import { otherFiltersItem } from '@/utils'

import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { filterURL } from '@/utils'
export default {
  name: 'FileEditForm',
  components: { ElImageViewer },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    rowData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      fileList: [],
      filterURL,
      attachmentTypeObj: {},
      otherFiles: [],
      delFiles: [],
      imgDialogVisible: false,
      previewImgs: [],
      url: '/pdf-file/',
      fileTypeName: '',
      attTypeOptions: [], // 附件类型
      formData: [],
      formRules: {
        attachmentTypeId: [
          { required: true, message: '请选择附件类型', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
  },
  created() {
    this.getAttachmentType()
    this.loading = true
    queryDetail(this.rowData.id).then(res => {
      if (res.success) {
        this.fileList = res.data.shopAttachmentDTOList.filter(v => v.attachmentType === '单号图纸')
        this.otherFiles = res.data.shopAttachmentDTOList.filter(v => v.attachmentType !== '单号图纸')
        this.loading = false
      }
    }).catch(() => {
      this.loading = false
    })
  },
  methods: {

    // 删除附件
    handleDelete(id, index) {
      if (id) {
        const list = this.fileList
        list.forEach((item, index) => {
          if (item.id === id) {
            this.delFiles.push({ ...item, dr: 1 })
          }
        })
      }
      this.fileList.splice(index, 1)
    },
    handleSelectionChange(val) {
      this.$emit('select', val)
    },
    handleCloseImg() {
      this.imgDialogVisible = false
    },
    handlePreview(file, keyIndex) {
      const fileExtension = file.attachmentUrl.substring(file.attachmentUrl.lastIndexOf('.') + 1).toLowerCase()
      if (fileExtension === 'pdf') {
        // pdf预览
        const url = this.url + file.attachmentUrl
        const routeData = this.$router.resolve({
          path: '/viewFile',
          query: {
            src: btoa(url)
          }
        })
        window.open(routeData.href, '_blank')
      } else if (fileExtension === 'jpg' || fileExtension === 'jpeg' || fileExtension === 'png' || fileExtension === 'gif') {
      // 图片预览
        this.imgDialogVisible = true
        this.previewImgs = [...this.fileList.slice(keyIndex), ...this.fileList.slice(0, keyIndex)]
        this.previewImgs = this.previewImgs.map(v => filterURL(v.attachmentUrl))
      } else if (fileExtension === 'doc' || fileExtension === 'docx' || fileExtension === 'xlsx' || fileExtension === 'excel') {
        // word,excel预览
        window.open('http://oos.quanyou.com.cn/op/view.aspx?src=' + filterURL(file.attachmentUrl))
      } else {
        this.$message.warning('该文件类型不支持预览')
      }
    },
    // 获取文件数据
    getFile(event) {
      const list = event.target.files
      const formFile = new FormData()
      for (let i = 0; i < list.length; i++) {
        formFile.append('files', list[i])
      }
      // 调用接口
      fileUploadBatch(formFile).then(response => {
        response.data.forEach(el => {
          const imgItem = {
            attachmentName: (el && el.attachmentName) || '', // 附件名
            attachmentUrl: el && el.attachmentUrl, // 文件路径
            attachmentType: this.attachmentTypeObj.attachmentType,
            belongModel: 'SELF_DESIGN',
            configAttachmentId: this.attachmentTypeObj.id,
            modelId: this.rowData.id,
            isHandle: 1,
            id: el.id,
            typeName: el && el.typeName, // 文件格式
            addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
            createTime: (el && el.createTime) || '', // 创建时间
            createBy: (el && el.createBy) || '', // 创建人
            dr: (el && el.dr) || 0 // 删除标志
          }
          this.fileList.push(imgItem)
        })
      }).catch(() => {
      })
    },
    handleAdd() {
      this.$refs.fileInput.click()
    },
    // 获取附件类型attachmentType下拉选项
    getAttachmentType() {
      const data = new FormData()
      data.append('filtersRaw', JSON.stringify([otherFiltersItem('belongModel', 'SELF_DESIGN', '=')]))
      postConfigAttachmentTemplate(data).then(res => {
        console.log(res)
        if (res.success === 1) {
        // 根据modelId获取每个配置id
          const temp = res.data.records.filter(el => el.enable === 1 && (el.attachmentType === '单号图纸'))
          if (temp.length > 0) this.attachmentTypeObj = temp[0]
        }
      })
    },
    // 删除文件
    removeFile(data) {
      this.fileList = data.list
    },
    // 文件上传成功
    uploadSuccessFile(data) {
      this.fileList = data.list
    },
    closeDialog() {
      this.dialogShow = false
      this.loading = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = []
      done && done()
    },
    // 提交表单处理
    submitForm(type) {
      if (this.fileList.length === 0) {
        this.$message.warning('请上传文件')
        return
      }
      const submitData = {
        id: this.rowData.id,
        shopAttachmentDTOList: [...this.fileList, ...this.otherFiles, ...this.delFiles] }
      this.loading = true
      saveOrderPicUpload(submitData, type).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.closeDialog()
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.file-box{
  width: 40px;
  height: 40px;
  display:flex;
  align-items: center;
  justify-content: center;
  color:#888;
  background-color: #f1eeee;
  margin :5px;
}
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
</style>
